# -*- coding: utf-8 -*-
"""
@Time ： 2024/7/5 18:04
@Auth ： 九问
@File ：tools.py
@IDE ：PyCharm
@Email : 2750826557@qq.com
"""
import random
import string
from concurrent.futures import ThreadPoolExecutor
from TestHub.settings import client
from captcha.image import ImageCaptcha
import logging

logger = logging.getLogger(__name__)


class MyCaptchaImage:
    def __init__(self):
        self.characters = string.digits + string.ascii_uppercase + string.ascii_lowercase
        self.width = 170
        self.height = 80
        self.n_len = 4
        self.n_class = len(self.characters)

    def generate_code(self):
        generator = ImageCaptcha(width=self.width, height=self.height)
        random_str = ''.join([random.choice(self.characters) for j in range(self.n_len)])
        img = generator.generate_image(random_str)
        return img, random_str


class ThreadImgs:
    def __init__(self):
        self.image_list = []

    def thread_function(self, file):
        images_ext_name = ''
        try:
            if file.content_type:
                if not file or file.content_type not in (
                        'image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/avif', "video/mp4"):
                    # 不是，返回客户端传入数据错误
                    return
                try:
                    images_ext_name = file.name.split('.')[-1]
                except Exception as e:
                    logger.info('图片拓展名异常：%s' % e)
                    images_ext_name = 'png'
        except:
            if file.name.split('.')[-1] not in ('jpeg', 'png', 'gif', 'jpg', 'webp', 'avif', 'mp4'):
                return
            # 得到文件后缀名，如果没有后缀名则默认为png类型
            try:
                images_ext_name = file['name'].split('.')[-1]
            except Exception as e:
                logger.info('文件拓展名异常：%s' % e)
                images_ext_name = 'png'

        try:
            upload_res = client.upload_by_buffer(file.read(), file_ext_name=images_ext_name)
        except Exception as e:
            return logger.error('文件上传出现异常：%s' % e)
        else:
            if upload_res.get('Status') != 'Upload successed.':
                return logger.warning('文件上传失败')
                # 得到返回的file_id
            self.image_list.append(upload_res.get('Remote file_id').decode())

    def circulate_add_file(self, files):
        executor = ThreadPoolExecutor(max_workers=5)
        # 并行处理每个元素
        if files:
            for img in files:
                executor.submit(self.thread_function, img)
            # 等待所有线程处理完毕，返回结果
            executor.shutdown(wait=True)

    def clear(self):
        self.image_list = []
